<template>
  <view class="main_div">
    <!-- 顶部导航栏 -->
    <view class="main_div_img" @click="goToMap">
      <image
        src="/static/images/icon/dingwei.png"
        class="main_div_img_img"
      ></image>
      <text class="main_div_img_text">{{ schoolName }}</text>
      <image
        src="/static/images/icon/xiajiantou.png"
        class="main_div_img_img2"
      ></image>
    </view>

    <!-- 轮播图 -->
    <view class="main_div_swiper">
      <swiper-component :swiper-list="list1"></swiper-component>
    </view>

    <!-- 滚动公告 -->
    <view class="main_div_notice">
      <view class="notice-content">
        <text class="notice-text" speed="500" mode="vertical">{{ text1 }}</text>
      </view>
    </view>

    <!-- 宫格布局 -->
    <grid-component :grid-list="gridlist" @grid-click="handleGridClick" />

    <!-- 动态列表 -->
    <dynamics-list
      :dynamics-list="dynamicsList"
      :loading="loading"
      :no-more="false"
      :liked-items="new Set()"
    />

    <!-- 悬浮球组件 -->
    <hover-ball
      :image-url="ballImageUrl"
      :target-path="ballTargetPath"
      :navigate-type="ballNavigateType"
      :initial-position="ballInitialPosition"
      :size="ballSize"
      @ball-click="onBallClick"
    />

    <!-- <up-toast ref="uToastRef" /> -->
  </view>
</template>

<script>
import { ref, onMounted } from "vue";
import "../csspages/main.css";
import SwiperComponent from "../../zujian/swiper.vue";
import GridComponent from "../../zujian/grid.vue";
import HoverBall from "../../zujian/hoverball.vue";
import DynamicsList from "../../zujian/main_dynamics_list.vue";
import axios from "axios";
export default {
  components: {
    SwiperComponent,
    GridComponent,
    HoverBall,
    DynamicsList,
  },
  onShow() {
    console.log("main.vue onShow");
    // 直接检查全局数据并更新
    const app = getApp();
    if (app && app.globalData && app.globalData.selectedSchoolName) {
      console.log("检测到全局学校名称:", app.globalData.selectedSchoolName);
      // 使用 nextTick 确保 DOM 更新
      this.$nextTick(() => {
        if (this.schoolName !== undefined) {
          this.schoolName = app.globalData.selectedSchoolName;
          console.log("学校名称已更新为:", this.schoolName);
          delete app.globalData.selectedSchoolName;
        }
      });
    }
  },
  setup() {
    // const uToastRef = ref(null);
    const schoolName = ref("保定理工学院"); // 默认学校名称
    const ballImageUrl = ref("/static/images/img/xuanfu.jpg");
    const ballTargetPath = ref("/pages/JJK/qiang");
    const ballNavigateType = ref("navigateTo");
    const ballInitialPosition = ref("bottomRight");
    const ballSize = ref(60);
    const dynamicsList = ref([]);
    const loading = ref(false);

    const getDynamicsList = async () => {
      try {
        loading.value = true;
        // console.log('开始获取动态列表数据...');
        const res = await axios.get("/h5api/ltc/essay/list");
        // console.log('获取到的动态数据:', res);
        // 根据后端返回格式，res 应该是 { code, msg, data }
        // 但 http 拦截器已经处理了响应，直接返回 data
        dynamicsList.value = Array.isArray(res.data.data) ? res.data.data : [];
        // console.log('dynamicsList 已更新:', dynamicsList.value);
      } catch (error) {
        console.error("获取动态列表失败:", error);
        uni.showToast({
          title: "获取动态列表失败",
          icon: "none",
        });
      } finally {
        loading.value = false;
      }
    };
    const list1 = ref([
      "/static/images/img/lunbo/lunbo1.jpg",
      "/static/images/img/lunbo/lunbo2.jpg",
      "/static/images/img/lunbo/lunbo3.png",
      "/static/images/img/lunbo/lunbo4.jpeg",
      "/static/images/img/lunbo/lunbo6.png",
    ]);
    const text1 = ref(
      "欢迎来到保定理工学院欢迎来到保定理工学院欢迎来到保定理工学院欢迎来到保定理工学院"
    );
    const gridlist = ref([
      {
        name: "/static/images/grid/Notice.png",
        title: "代取须知",
        path: "./notice",
      },
      {
        name: "/static/images/grid/express_delivery.png",
        title: "快递代取",
        path: "/pages/express-pickup/express-pickup",
      },
      {
        name: "/static/images/grid/Takeaway.png",
        title: "外卖代取",
        path: "/pages/food-pickup/food-pickup",
      },
      {
        name: "/static/images/grid/authentication.png",
        title: "骑手认证",
        path: "./authentication",
      },
      {
        name: "/static/images/grid/trade.png",
        title: "闲置交易",
      },
    ]);
    onMounted(() => {
      console.log("main.vue mounted");
      try {
        checkForSchoolName();
        // 获取动态列表数据
        getDynamicsList();
      } catch (error) {
        console.error("onMounted 执行错误:", error);
      }
    });

    // 检查并更新学校名称
    const checkForSchoolName = () => {
      try {
        const app = getApp();
        if (app && app.globalData && app.globalData.selectedSchoolName) {
          schoolName.value = app.globalData.selectedSchoolName;
          console.log("从全局数据更新学校名称:", schoolName.value);
          // 清除全局数据
          delete app.globalData.selectedSchoolName;
        }
      } catch (error) {
        console.error("checkForSchoolName 执行错误:", error);
      }
    };

    // 暴露给组件实例的方法，供 onShow 使用
    const updateSchoolNameFromGlobal = () => {
      checkForSchoolName();
    };
    const handleGridClick = (name) => {
      if (name.path) {
        uni.navigateTo({
          url: name.path,
        });
      // } else if (uToastRef.value) {
      //   uToastRef.value.success(`点击了${name.title}`);
    } else {
        uni.showToast({
          title: `点击了${name.title}`,
          icon: 'none'
        });
      }
    };
    const goToMap = () => {
      uni.navigateTo({
        url: "./map",
      });
    };
    const onBallClick = (data) => {
      // console.log('悬浮球被点击:', data);

      if (data.clickType === "single") {
        // 单击事件
        // uni.showToast({
        //   title: '单击悬浮球',
        //   icon: 'none',
        //   duration: 1000
        // });
      } else if (data.clickType === "double") {
        // // 双击事件
        // uni.showToast({
        //   title: '正在跳转到动态详情...',
        //   icon: 'success',
        //   duration: 1000
        // });
      }
    };

    // 更新学校名称的方法（供其他页面调用）
    const updateLocationName = (name) => {
      schoolName.value = name;
      console.log("学校名称已更新为:", name);
    };
    return {
      // uToastRef,
      schoolName,
      handleGridClick,
      goToMap,
      onBallClick,
      updateLocationName,
      updateSchoolNameFromGlobal,
      ballImageUrl,
      ballTargetPath,
      ballNavigateType,
      ballInitialPosition,
      ballSize,
      list1,
      text1,
      gridlist,
      dynamicsList,
      loading,
      getDynamicsList,
    };
  },
};
</script>